<template>
  <div>
    <el-dialog
      title="采集评论"
      width="60%"
      v-loading="loading"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <div>
        <el-form ref="dataForm" :model="dataForm" label-width="80px">
          <el-form-item label="淘宝url">
            <el-row :gutter="20">
               <el-col :span="15">
                <el-input v-model="dataForm.url" style="width: 400px"></el-input>
              </el-col>
              <el-col :span="5">
                <el-button type="primary" @click="startCollect">立即采集</el-button>
              </el-col>
            </el-row>
            <el-row v-if="commentList.length!==0">
              <!-- <el-col>
                <span style="color: #909399 ;font-size: 10px">为您采集到{{commentList.length}}条评论，不上传用户头像，会默认已默认头像填充</span>
              </el-col> -->
            </el-row>
          </el-form-item>
          <el-form-item label="商品ID">
            <el-row :gutter="20">
               <el-col :span="15">
                <el-input v-model="dataForm.id" style="width: 165px"></el-input>&nbsp;&nbsp;<span>&nbsp;&nbsp;页数：</span><el-input style="width: 100px" type="number" v-model="dataForm.dataPage"></el-input>&nbsp;&nbsp;<span>&nbsp;&nbsp;拉取数据条数：</span><el-input style="width: 120px" type="number" v-model="dataForm.numberOfBars"></el-input>
              </el-col>
              <el-col :span="5">
                <el-button type="primary" @click="startCollectId">立即采集</el-button>
              </el-col>
            </el-row>
            <el-row v-if="commentList.length!==0">
              <el-col>
                <span style="color: #909399 ;font-size: 10px">为您采集到{{commentList.length}}条评论，不上传用户头像，会默认已默认头像填充</span>
              </el-col>
            </el-row>
            <el-row v-if="commentList.length===0">
              <el-col>
                <span style="color: #909399 ;font-size: 10px">为您采集到{{commentList.length}}条评论，不上传用户头像，会默认已默认头像填充</span>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="商品ID">
              <el-row :gutter="20">
                <el-col :span="15">
                  <el-input v-model="dataForm.goodsCollectionId" style="width: 400px"/> <el-button type="primary" @click="handleInsertComment" v-if="dataForm.goodsCollectionId != ''">评论插入</el-button>
                </el-col>
                <el-col :span="5">
                  <el-button type="primary" @click="immediatelyCollect">立即采集</el-button>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <span style="color: #909399 ;font-size: 10px">为您采集到{{commentList.length}}条评论，不上传用户头像，会默认已默认头像填充,此操作为采集本地库商品评论</span>
                </el-col>
              </el-row>
          </el-form-item>
        </el-form>


        <el-card shadow="always" style="max-width: 95%;margin-left: 2%;box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);"
                 v-if="commentList.length!==0">
          <el-table
            :data="commentList"
            stripe
            height="500"
            border
            style="width: 100%;">
            <el-table-column
              prop="headImg"
              label="用户头像">
              <template slot-scope="scope">
                <el-upload
                  class="avatar-uploader"
                  :action="url"
                  :show-file-list="false"
                  :on-success="((res, file, fileList) => {handleAvatarSuccess(res, file, fileList ,scope.$index)})"
                  :before-upload="checkFile">
                  <img v-if="scope.row.headImg" :src="scope.row.headImg" class="avatar" style="max-height: 30px;max-width: 80px">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column
              prop="realName"
              label="用户名"
              width="150">
              <template slot-scope="scope">
                <el-input style="width: 130px" size="mini" v-model="scope.row.realName"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="userId"
              label="评论者ID"
              width="150"
              v-if="false">
              <template slot-scope="scope">
                <span>{{scope.row.userId}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="content"
              label="内容"
              width="300">
              <template slot-scope="scope">
                <!-- <el-input type="textarea" :rows="1" v-model="scope.row.content"></el-input> -->
                <el-popover
                  style="margin-left: 5px;margin-bottom: 5px"
                  placement="right"
                  title=""
                  trigger="hover">
                  <el-input type="textarea" v-if="scope.row.content !== null" v-model="scope.row.content" :autosize ="{ minRows: 20, maxRows: 40 }"/>
                  <el-input type="textarea" slot="reference" v-if="scope.row.content !== null" v-model="scope.row.content" style="max-height: 30px;max-width: 800px"/>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              prop="commentImages"
              label="评论图片">
              <template slot-scope="scope">
                <el-popover
                  style="margin-left: 5px;margin-bottom: 5px"
                  placement="right"
                  title=""
                  trigger="hover" v-for="(item, index) in scope.row.commentImages" :key="index">
                  <img v-if="item !== null" :src="item" style="max-width: 300px"/>
                  <img slot="reference" v-if="item !== null" :src="item" :alt="item" style="max-height: 30px;max-width: 80px"/>
                </el-popover>
                <el-button type="text" size="small" @click="photoSetHandle(scope.row.commentImages,scope.$index)"
                           style="padding: 19px 0px 0px 0px;float: right;">更多...</el-button>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              width="200"
              label="时间">
              <template slot-scope="scope">
                <el-date-picker
                  style="width: 180px;"
                  v-model="scope.row.createTime"
                  type="datetime"
                  size="mini"
                  value-format = "yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              width="60"
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="removeComment(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button style="float:left" type="primary" @click="addComment" >添加</el-button>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleAddComment" >确定</el-button>
    </span>
    </el-dialog>

    <el-dialog
      title="评论图片集"
      :visible.sync="photoSetVisible"
      width="50%">
      <div>
        <el-upload
          :action="url"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :file-list="photoSet"
          :on-remove="handleRemove"
          :on-success="handlePhotoSetSuccess">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="photoVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="photoSetVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyCommentPhotoSet">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios'
import { setTimeout } from 'timers';
  export default {
    data: function () {
      return {
        loading: false,
        visible: false,
        dataListLoading: false,
        goodsId: 0,
        commentList: [],
        photoSet: [],
        photoSetVisible: false,
        photoSetIndex: 0,
        photoVisible: false,
        dialogImageUrl: '',
        url: '',
        dataForm: {
          goodsCollectionId: '',
          url: '',
          id: '',
          numberOfBars: 50,
          dataPage: 1
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.url = ''
        this.dataForm.id = ''
        this.commentList = []
        this.url = this.$http.adornUrl(`/sys/tools/uploadImg/comments?token=${this.$cookie.get('token')}`)
        this.visible = true
        this.goodsId = id
        this.dataForm.dataPage = 1
      },
      startCollect () {
        this.loading = true
        let goodsId = ''
        let url = this.dataForm.url
        if (url) {
          goodsId = url.substring(url.indexOf('id=') + 3, url.lastIndexOf('&'))
          goodsId = goodsId.substring(0, goodsId.indexOf('&'))
        } else {
          this.$message('url不能为空')
          return
        }
        if (!goodsId) {
          this.$message('非法的url')
          return
        }
        axios.post('http://component.yilianbaihui.cn:8000/getGoodsCommentById', JSON.stringify({
          'goodsId': goodsId
        })).then(({data}) => {
          this.loading = false
          if (data && data.code === 200) {
            debugger
            this.commentList = data.data || []
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      startCollectId () {
        if (this.dataForm.numberOfBars == null || this.dataForm.numberOfBars <= 0 || this.dataForm.numberOfBars > 500) {
          this.$message.error('拉取的数据必须大于0且小于500')
          return
        }
        this.$http({
          url: this.$http.adornUrl(`/good/comment/getGoodsComments/${this.dataForm.id}/${this.dataForm.numberOfBars}/${this.dataForm.dataPage}`),
          method: 'post',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.commentList = data.data || []
            if (this.commentList.length === 0) {
              this.$message('未拉取到数据！')
            }
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      immediatelyCollect () {
        this.$http({
          url: this.$http.adornUrl(`/good/comment/getGoodsComments/${this.dataForm.goodsCollectionId}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.commentList = data.data || []
            if (this.commentList.length === 0) {
              this.$message('未拉取到数据！')
            }
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      checkFile (file) {
        let suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (suffix !== 'jpg' && suffix !== 'png') {
          this.$message.error('上传文件只能是 jpg、png格式!')
          return false
        }

        if (file.size > 1024 * 1024) {
          this.$message.error('上传图片大小不能超过1M！')
          return false
        }
      },
      handleAvatarSuccess (res, file, fileList, index) {
        debugger
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 1000
        })
        if (res.code === 0) {
          this.$set(this.commentList[index], 'headImg', res.data)
        }
      },
      handleRemove (file, fileList) {
        let index = this.photoSetIndex
        for (var i = 0; i < this.commentList[index].commentImages.length; i++) {
          if (file.url === this.commentList[index].commentImages[i]) {
            this.commentList[index].commentImages.splice(i, 1)
            this.photoSet.splice(i, 1)
            return
          }
        }
        // setTimeout(this.deleteCommentImg(file, fileList), 3000)
        // fileList.map(list => {
        //   if (list.uid === file.uid) {
        //     fileList.remove(list)
        //   }
        // })
      },
      handlePhotoSetSuccess (res, file, fileList) {
        if (res.code !== 0) {
          this.$message.error(res.msg)
          return
        }
        fileList.map(list => {
          if (list.uid === file.uid) {
            file.url = res.data
          }
        })
        this.photoSet = fileList
      },
      modifyCommentPhotoSet () {
        this.photoSetVisible = false
        this.$set(this.commentList[this.photoSetIndex], 'commentImages', this.photoSet.map(photo => {
          return photo.url
        }))
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.photoVisible = true
      },
      photoSetHandle (photoList, index) {
        let than = this
        than.photoSet = []
        photoList.map(list => {
          // if (list.indexOf('http') === -1 || list.indexOf('https') === -1) {
          //   list = 'https:' + list
          // }
          than.photoSet.push({url: list})
        })
        this.photoSetIndex = index
        this.photoSetVisible = true
      },
      handleInsertComment () {
        this.$confirm(`确定插入到商品评论吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/good/comment/insertComment/${this.goodsId}`),
            method: 'post',
            data: this.$http.adornData(this.commentList, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 800,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      handleAddComment () {
        // let refererUrl = this.dataForm.url
        if (this.dataForm.url !== '') {
          for (var i = 0; i < this.commentList.length; i++) {
            this.$set(this.commentList[i], 'refererUrl', this.dataForm.url)
            console.log(this.commentList[i])
          }
        }
        debugger
        console.log(this.goodsId)
        this.$confirm(`确定插入到商品评论吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/good/comment/addTimingComment/${this.goodsId}`),
            method: 'post',
            data: this.$http.adornData(this.commentList, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 800,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      removeComment (index) {
        this.commentList.splice(index, 1)
      },
      // 自行添加评论信息
      addComment () {
        this.commentList.push({commentImages: [], content: '', realName: '', headImg: '', createTime: ''})
      }
    }
  }
</script>
<style>
  .characters{
    width:300px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }
</style>
